<template>
	<view class="page-wrapper">
		<view class="container">
			<swiper class="swiper" :indicator-dots="true" :autoplay="true" interval="3000" duration="1000" 
				indicator-color="rgba(255,255,255,0.6)" indicator-active-color="#ffffff">
				<swiper-item v-for="(item, index) in swiperList" :key="index">
					<image :src="item.image" class="swiper-image" mode="aspectFill" />
				</swiper-item>
			</swiper>
			<view class="header">
				<text class="title">梧悠杨简装全案</text>
				<text class="subtitle">装修报价器，精准估算，省心省钱，快速出结果。</text>
			</view>
			<view class="package-section">
				<view class="package-title">选择装修套餐</view>
				<scroll-view scroll-x="true" class="package-scroll">
					<view class="package-list">
						<view 
							v-for="(item, index) in packageTypes" 
							:key="index" 
							:class="['package-item', { active: selectedPackage === item.value }]"
							@click="selectPackage(item.value)"
						>
							<view class="package-icon">
								<uni-icons :type="item.icon" size="24" :color="selectedPackage === item.value ? '#fff' : '#e93b3d'" />
							</view>
							<view class="package-content">
								<text class="package-name">{{item.name}}</text>
								<text class="package-desc">{{item.desc}}</text>
<!--								<text class="package-price">¥{{item.basePrice}}/㎡起</text>-->
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
			<view class="form-section">
				<view class="section-title">
					<view class="title-line"></view>
					<text class="title-text">基本信息</text>
				</view>
				
				<!-- 新增房屋面积输入 -->
				<view class="form-item" style="height: 35px;">
					<view class="form-item-row">
						<view class="label-container">
							<text class="label">房屋面积</text>
							<text class="label-desc">单位：平方米</text>
						</view>
						<view class="input-container">
							<input 
								type="number" 
								class="area-input" 
								placeholder="请输入房屋面积"
								v-model="houseArea"
							/>
						</view>
					</view>
				</view>

				<!-- 原房间数量表单项 -->
				<view class="form-item" style="height: 35px;">
					<view class="form-item-row">
						<view class="label-container">
							<text class="label">房间数量</text>
							<text class="label-desc">卧室数量</text>
						</view>
						<view class="counter">
							<view class="counter-btn" :class="{'disabled': roomCount <= 1}" @click="decreaseCount('room')">
								<uni-icons type="minus" size="18" :color="roomCount <= 1 ? '#ccc' : '#e93b3d'" />
							</view>
							<text class="counter-number">{{roomCount}}</text>
							<view class="counter-btn" :class="{'disabled': roomCount >= 5}" @click="increaseCount('room')">
								<uni-icons type="plus" size="18" :color="roomCount >= 5 ? '#ccc' : '#e93b3d'" />
							</view>
						</view>
					</view>
				</view>
<!--				<view class="form-item">-->
<!--					<view class="form-item-row">-->
<!--						<view class="label-container">-->
<!--							<text class="label">厨房数量</text>-->
<!--						</view>-->
<!--						<view class="counter">-->
<!--							<view class="counter-btn" :class="{'disabled': kitchenCount <= 0}" @click="decreaseCount('kitchen')">-->
<!--								<uni-icons type="minus" size="18" :color="kitchenCount <= 0 ? '#ccc' : '#e93b3d'" />-->
<!--							</view>-->
<!--							<text class="counter-number">{{kitchenCount}}</text>-->
<!--							<view class="counter-btn" :class="{'disabled': kitchenCount >= 2}" @click="increaseCount('kitchen')">-->
<!--								<uni-icons type="plus" size="18" :color="kitchenCount >= 2 ? '#ccc' : '#e93b3d'" />-->
<!--							</view>-->
<!--						</view>-->
<!--					</view>-->
<!--				</view>-->
				<view class="form-item" style="height: 35px;">
					<view class="form-item-row">
						<view class="label-container">
							<text class="label">卫生间数量</text>
						</view>
						<view class="counter">
							<view class="counter-btn" :class="{'disabled': bathroomCount <= 1}" @click="decreaseCount('bathroom')">
								<uni-icons type="minus" size="18" :color="bathroomCount <= 1 ? '#ccc' : '#e93b3d'" />
							</view>
							<text class="counter-number">{{bathroomCount}}</text>
							<view class="counter-btn" :class="{'disabled': bathroomCount >= 3}" @click="increaseCount('bathroom')">
								<uni-icons type="plus" size="18" :color="bathroomCount >= 3 ? '#ccc' : '#e93b3d'" />
							</view>
						</view>
					</view>
				</view>
				<view class="form-item" style="height: 35px;margin-bottom: 20px;">
					<view class="form-item-row">
						<view class="label-container">
							<text class="label">是否公寓</text>
						</view>
						<view class="radio-group">
							<view class="radio-item" @click="isApartment = true">
								<view :class="['radio-circle', { active: isApartment }]" />
								<text class="radio-label">是</text>
							</view>
							<view class="radio-item" @click="isApartment = false">
								<view :class="['radio-circle', { active: !isApartment }]" />
								<text class="radio-label">否</text>
							</view>
						</view>
					</view>
				</view>
				<template v-if="isApartment">
					<view class="section-title">
						<view class="title-line"></view>
						<text class="title-text">公寓信息</text>
					</view>
					<view class="form-item">
						<view class="form-item-row">
							<view class="label-container">
								<text class="label">公寓类型</text>
							</view>
							<view class="radio-group">
								<view class="radio-item" @click="apartmentType = 1">
									<view :class="['radio-circle', { active: apartmentType === 1 }]" />
									<text class="radio-label">平层</text>
								</view>
								<view class="radio-item" @click="apartmentType = 2">
									<view :class="['radio-circle', { active: apartmentType === 2 }]" />
									<text class="radio-label">复式</text>
								</view>
							</view>
						</view>
					</view>
					<view class="form-item" v-if="apartmentType === 2">
						<view class="form-item-row">
							<view class="label-container">
								<text class="label">复式类型</text>
								<text class="label-desc">影响空间规划</text>
							</view>
						</view>
						<view class="duplex-options">
							<view 
								v-for="(option, index) in duplexOptions" 
								:key="index"
								:class="['duplex-option', { active: selectedDuplexOption === option.value }]"
								@click="selectedDuplexOption = option.value"
							>
								<image :src="option.image" class="duplex-image" mode="aspectFill" />
								<view class="duplex-info">
									<text class="duplex-name">{{option.name}}</text>
									<text class="duplex-desc">{{option.desc}}</text>
								</view>
							</view>
						</view>
					</view>
					<view class="form-item">
						<view class="form-item-row">
							<view class="label-container">
								<text class="label">是否装厨房门</text>
								<text class="label-desc">影响整体报价</text>
							</view>
							<view class="radio-group">
								<view class="radio-item" @click="hasKitchenDoor = true">
									<view :class="['radio-circle', { active: hasKitchenDoor }]" />
									<text class="radio-label">是</text>
								</view>
								<view class="radio-item" @click="hasKitchenDoor = false">
									<view :class="['radio-circle', { active: !hasKitchenDoor }]" />
									<text class="radio-label">否</text>
								</view>
							</view>
						</view>
					</view>
				</template>
			</view>
			<view class="button-section">
				<view class="price-estimate" v-if="estimatedPrice > 0">
					<text class="price-label">估算价格</text>
					<text class="price-value">¥{{estimatedPrice}}</text>
				</view>
				 <button class="submit-button" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">获取精准报价</button>
<!--       <button class="action-btn" @tap="testJump()">获取报价</button>-->
			</view>
		</view>
		
		<!-- 修改弹窗内容，只显示提交成功信息 -->
		<uni-popup ref="popup" type="center">
			<view class="popup-content">
				<view class="popup-title">提交成功</view>
				<view class="popup-desc">我们将尽快与您联系，为您提供精准报价</view>
				<view class="popup-icon">
					<uni-icons type="checkmarkempty" size="60" color="#e93b3d" />
				</view>
				<view class="popup-buttons">
					<button class="popup-submit full-width" @click="closePopup">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
// 引入必要的组件
import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue'
import {httpNoLoginRequest} from "../../utils/http";

export default {
	name: 'CalWx',
	components: {
		uniIcons,
		uniPopup
	},
	data() {
		return {
			swiperList: [
				{
					image: 'https://ai-public.mastergo.com/ai/img_res/597e4899fc82c49bbf2bdb52053b6180.jpg'
				},
				{
					image: 'https://ai-public.mastergo.com/ai/img_res/917d7b179840c83ae8951d7410a917dd.jpg'
				},
				{
					image: 'https://ai-public.mastergo.com/ai/img_res/7edd999b018749c27388ae460315fe9e.jpg'
				}
			],
      userId:null,
      cpId:null,
      sessionKey:null,
      houseArea: null,
			roomCount: 1,
			kitchenCount: 1,
			bathroomCount: 1,
			isApartment: false,
			apartmentType: 1,
			hasKitchenDoor: false,
			phone: '',
			verifyCode: '',
			countDown: 0,
			isCountingDown: false,
			countDownText: '获取验证码',
			estimatedPrice: 0,
			selectedPackage: '1',
			packageTypes: [
				{
					value: '1',
					name: '优选',
					desc: '品质保障，性价比高',
					// basePrice: 580,
					icon: 'home'
				},
				{
					value: '2',
					name: '悦享',
					desc: '精致生活，舒适体验',
					// basePrice: 880,
					icon: 'star'
				},
				{
					value: '3',
					name: '极速',
					desc: '基础装修，经济实惠',
					// basePrice: 680,
					icon: 'location'
				},
        {
          value: '4',
          name: '尊享',
          desc: '高端定制，奢华享受',
          // basePrice: 680,
          icon: 'location'
        }
			],
			duplexOptions: [
				{
					value: '1',
					name: 'loft公寓1房',
					desc: '适合小户型，空间紧凑，功能齐全。',
					image: 'https://ai-public.mastergo.com/ai/img_res/597e4899fc82c49bbf2bdb52053b6180.jpg'
				},
				{
					value: '2',
					name: 'loft公寓2房',
					desc: '适合中户型，双层设计，动静分区。',
					image: 'https://ai-public.mastergo.com/ai/img_res/917d7b179840c83ae8951d7410a917dd.jpg'
				},
				{
					value: '3',
					name: '双钥匙分户',
					desc: '两套独立居住空间，一房两户，独立出入。',
					image: 'https://ai-public.mastergo.com/ai/img_res/7edd999b018749c27388ae460315fe9e.jpg'
				}
			],
			selectedDuplexOption: '1'
		}
	},
  onLoad(options) {
    if (options.scene) {
      const scene = decodeURIComponent(options.scene); // 解码一次即可
      console.log('接收到的参数:', scene); // 输出: id=123&target=product
      const params = this.parseQueryString(scene);      // 解析为对象
      for (let key in params) {
        console.log(`参数名: ${key}, 参数值: ${params[key]}`);
        if(key=="uid"){
          this.userId = params[key];
          console.info("userId:"+this.userId);
        }else if(key=="cid") {
          this.cpId = params[key];
          console.info("cpId:" + this.cpId);
        }
      }
    }else{
      //分享获取
      // console.info("userId2:"+options.uid);
      // console.info("cpId2:"+options.cid);
      this.userId = options.uid;
      this.cpId = options.cid;
    }
  },
	computed: {
		apartmentTypes() {
			return [
				{ value: 'loft1', text: 'Loft一层' },
				{ value: 'loft2', text: 'Loft两层' },
				{ value: 'normal', text: '普通公寓' }
			]
		}
	},
	watch: {
	},
	mounted() {
		// this.calculateEstimatedPrice()
	},
	methods: {
    parseQueryString(query) {
      const result = {};
      if (!query) return result;
      const pairs = query.split('&');
      for (let pair of pairs) {
        const [key, value] = pair.split('=');
        result[key] = value;
      }
      return result;
    },
    testJump(){
      if (this.$shopxPub.isEmpty(this.houseArea)) {
        uni.showToast({
          title: '请输入您的房屋面积',
          icon: 'none'
        });
        return;
      }
      var randomNum = Math.floor(10000000 + Math.random() * 90000000);
      var model={
        renovationType:  this.selectedPackage,
        houseArea: this.houseArea,
        houseNum: this.roomCount,
        kitchenNum: this.kitchenCount,
        toiletNum: this.bathroomCount,
        singleFlag: this.isApartment==true?"1":"2",
        houseType: this.apartmentType,
        compoundType: this.selectedDuplexOption,
        kitchenDoorFlag: this.hasKitchenDoor==true?"1":"2",
        salesman:this.$shopxPub.isEmpty(this.userId)?"123456":this.userId,
        cpId:this.$shopxPub.isEmpty(this.cpId)?"100000":this.cpId,
        channelType:"1",
        openId:"1111",
        phone:"152"+randomNum
      }
      console.log('用户填写数据2:'+JSON.stringify(model));
      var that = this;
      that.$shopxHttp.httpNoLoginRequest({
        url: '/cmmCalPrice/calPrice',
        submitType: 'POST',
        data: model,
        successCallback: (res) => {
          uni.navigateTo({
            url: "/pages/cal/cal-suc?price="+res.rspData.price+"&userId="+that.userId+"&cpId="+that.cpId+"&houseInfo="+res.rspData.houseInfo+"&renovationTypeName="+res.rspData.renovationTypeName
          });
        },
        isSucAlert: 'y'
      });
    },
		decreaseCount(type) {
			switch (type) {
				case 'room':
					if (this.roomCount > 1) this.roomCount--
					break
				case 'kitchen':
					if (this.kitchenCount > 0) this.kitchenCount--
					break
				case 'bathroom':
					if (this.bathroomCount > 1) this.bathroomCount--
					break
			}
		},
		increaseCount(type) {
			switch (type) {
				case 'room':
					if (this.roomCount < 5) this.roomCount++
					break
				case 'kitchen':
					if (this.kitchenCount < 2) this.kitchenCount++
					break
				case 'bathroom':
					if (this.bathroomCount < 3) this.bathroomCount++
					break
			}
		},
		selectPackage(packageType) {
			this.selectedPackage = packageType
		},
		// sendPhoneNumberRequest(data) {
		// 	setTimeout(() => {
		// 		uni.hideLoading()
		// 		console.log('发送到服务器的数据:', data)
		// 		const mockPhoneNumber = '13812345678'
		// 		this.saveUserInfo(mockPhoneNumber, data.formData)
		// 		this.$refs.popup.open()
		// 	}, 1500)
		// },
		getPhoneNumber(e) {
      console.info("获取电话号码");
      if (this.$shopxPub.isEmpty(this.houseArea)) {
        uni.showToast({
          title: '请输入您的房屋面积',
          icon: 'none'
        });
        return;
      }
      //调用报价接口
      //暂时屏蔽掉获取手机号码的，有次数限制 todo
      this.isLoading = true;
      this.errorMessage = '';
      try {
        // 修正：将 res 替换为 e
        if (e.detail.errMsg !== 'getPhoneNumber:ok') {
          console.info("用户拒绝授权");
          throw new Error('用户拒绝授权');
        }
        // 使用 async/await 处理异步操作
        (async () => {
          const { code } = await new Promise((resolve, reject) => {
            uni.login({
              provider: 'weixin',
              success: resolve,
              fail: () => reject('登录失败，请重试'),
            });
          });
          // console.info("code:" + code);
          //示例：0b3NOl000qidcU1N5T200FOUmN1NOl0R
          // 调用登录接口获取 sessionKey`
          console.info("请求登录接口");
          var that = this;
          that.$shopxHttp.httpNoLoginRequest({
            url: '/wxMini/wxMiniLogin?code='+code,
            submitType: 'POST',
            data: {},
            successCallback: (res) => {
              console.info("请求接口成功:"+JSON.stringify(res));
              //示例: res：{"data":{"statusCode":"00000","statusDesc":"成功","rspData":{"sessionKey":"d4HdJESQuC1QqpBqiD8qSA==","openId":"oDDYW5rZMmwyHOCxqvZ_6M6EknX0"}},"header":{"Connection":"keep-alive","Vary":"Origin,Access-Control-Request-Method,Access-Control-Request-Headers","Transfer-Encoding":"chunked","Content-Type":"application/json","Date":"Mon, 05 May 2025 09:29:47 GMT"},"statusCode":200,"cookies":[],"accelerateType":"none","errMsg":"request:ok"}
              that.sessionKey = res.rspData.sessionKey;
              console.info("sessionKey:"+that.sessionKey);
              //示例：d4HdJESQuC1QqpBqiD8qSA==
              console.info("调用后台获取号码接口:"+'/wxMini/getPhoneNumber?code='+code);
              that.$shopxHttp.httpNoLoginRequest({
                url: '/wxMini/getPhoneNumber?code='+code,
                submitType: 'POST',
                data: {
                  encryptedData: e.detail.encryptedData,
                  iv: e.detail.iv,
                  sessionKey: that.sessionKey,
                },
                successCallback: (res) => {
                  console.info("调用后台获取号码接口成功:"+JSON.stringify(res));
                  var model={
                    renovationType:  this.selectedPackage,
                    houseArea: this.houseArea,
                    houseNum: this.roomCount,
                    kitchenNum: this.kitchenCount,
                    toiletNum: this.bathroomCount,
                    singleFlag: this.isApartment==true?"1":"2",
                    houseType: this.apartmentType,
                    compoundType: this.selectedDuplexOption,
                    kitchenDoorFlag: this.hasKitchenDoor==true?"1":"2",
                    salesman: that.userId,
                    cpId: that.cpId,
                    channelType:"1",
                    // openId:"1111",
                    phone: res.rspData.phoneNumber
                  }
                  that.$shopxHttp.httpNoLoginRequest({
                    url: '/cmmCalPrice/calPrice',
                    submitType: 'POST',
                    data: model,
                    successCallback: (res) => {
                      console.info("获取报价成功:"+JSON.stringify(res));
                      uni.navigateTo({
                        url: "/pages/cal/cal-suc?price="+res.rspData.price+"&userId="+that.userId+"&cpId="+that.cpId+"&houseInfo="+res.rspData.houseInfo+"&renovationTypeName="+res.rspData.renovationTypeName
                      });
                    },
                    isSucAlert: 'y'
                  });
                },
                isSucAlert: 'y'
              });


            },
            isSucAlert: 'y'
          });
        })();
      } catch (err) {
        console.info("err:" + JSON.stringify(err));
        this.errorMessage = err.message || '未知错误';
        uni.showToast({ title: '获取失败', icon: 'none' });
        console.error('获取手机号错误:', err);
      } finally {
        this.isLoading = false;
      }
		},
		closePopup() {
			this.$refs.popup.close()
		}
	}
}
</script>
<style lang="scss" scoped>
@import '@/pages/cal/cal-wx.scss';
</style>
